appropr <- appropr %>% mutate(cong_control = case_when(house_party == "D" & sen_party == "D" ~ "D", 
                                                       house_party == "R" & sen_party == "R" ~ "R",
                                                       TRUE ~ "Div"))

party_group_funding <- appropr %>% filter(house_party %in% c("D", "R")) %>%
                       group_by(house_party, major_group, fiscal_year) %>% 
                       summarise(total_funding = sum(pl_constant, na.rm = T))  

party_group_funding$major_group[is.na(party_group_funding$major_group)] <- "Other"


partisan_diff <- function(df, perm=TRUE){
  if (perm) {
    df$house_party <- sample(df$house_party)
  }
  (sum(df[df$house_party == "D",]$total_funding) / sum(df$house_party == "D")) - (sum(df[df$house_party == "R",]$total_funding) / sum(df$house_party == "R"))
}

permutation_diff_group <- function(group, T=1000) {
  df <- party_group_funding %>% filter(major_group == group)
  perms <- replicate(T, partisan_diff(df), simplify=TRUE)
  true_diff <- partisan_diff(df, perm=FALSE)
  two_tailed_pval <- sum(abs(perms) > abs(true_diff)) / T
  print(paste0("Permutation test of Partisan\nDifferences in ", group, " Funding"))
  p <- ggplot(data.frame(perms=perms), aes(x=perms)) + 
    geom_density() + 
    geom_vline(xintercept=partisan_diff(df, perm=FALSE)) +
    annotate("text", x=true_diff, y=0, label=paste0("p=", two_tailed_pval), hjust=-0.2, vjust=-40) +
    xlab("Sum Funding Under Democrats Less\nSum funding Under Republicans") + 
    ylab("Density") + 
    ggtitle(paste0("Permutation test of Partisan\nDifferences in ", group, " Funding"))
  ggsave(paste0(tolower(group), "_perms.png"), p)
  return(two_tailed_pval)
}

groups <- unique(party_group_funding$major_group)
pvals <- sapply(groups, 
                permutation_diff_group,
                simplify = FALSE, 
                USE.NAMES = TRUE)

adj_pvals <- p.adjust(pvals, "BH")
saveRDS(adj_pvals, file = "adj_pvals.rds") 
